package com.dys.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author: 疾风
 * @ClassName: SpringConfig
 * @Description: 通过配置类管理事务的使用
 * @CreateDate: 2024/10/22
 * @Version: v1.0.0
 */
@Configuration // 自定义Java配置类
@ComponentScan(basePackages = {"com.dys.*"}) // 指定扫描路径
@EnableTransactionManagement // 开启事务注解
public class SpringConfig {

    /**
     * 获取Druid连接池的 数据源,并将其注册为Spring的Bean组件
     *
     * @return DruidDataSource
     */
    @Bean
    public DataSource getDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring_jdbc_db?characterEncoding=utf8&useSSL=false&serverTimezone=UTC");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root123");
        return druidDataSource;
    }

    /**
     * 注册JdbcTemplate组件到Spring容器中
     *
     * @param dataSource 数据源
     * @return JdbcTemplate对象
     */
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        // 关联对应的数据源
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    /**
     * 注册DataSourceTransactionManager数据源事务管理器到Spring容器中
     *
     * @param dataSource 数据源
     * @return 事务管理器对象
     */
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(@Autowired DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        // 关联数据源
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
